package com.micro.ai.template.controller;

import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.AgentMetric;
import com.micro.ai.template.service.AgentMetricService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * Agent指标统计Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/agent/metrics")
@RequiredArgsConstructor
@Tag(name = "Agent指标统计", description = "Agent指标统计相关接口")
public class AgentMetricController {

    private final AgentMetricService agentMetricService;

    @PostMapping
    @PreAuthorize("hasAuthority('agent:metric:create')")
    @Operation(summary = "记录指标", description = "记录Agent的性能指标")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "记录成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限")
    })
    public ApiResponse<Void> recordMetric(@Valid @RequestBody AgentMetric agentMetric) {
        log.info("记录指标, agentId: {}", agentMetric.getAgentId());
        agentMetricService.recordMetric(agentMetric);
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/{agentId}")
    @PreAuthorize("hasAuthority('agent:metric:query')")
    @Operation(summary = "查询指标数据", description = "查询指定时间范围的Agent指标")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<List<AgentMetric>> getMetrics(
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Parameter(description = "开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        log.info("查询指标数据, agentId: {}, startTime: {}, endTime: {}", agentId, startTime, endTime);
        return ApiResponse.success(agentMetricService.getMetrics(agentId, startTime, endTime));
    }

    @GetMapping("/{agentId}/aggregated")
    @PreAuthorize("hasAuthority('agent:metric:query')")
    @Operation(summary = "查询聚合指标", description = "查询Agent的聚合统计指标")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "参数错误"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<Map<String, Object>> getAggregatedMetrics(
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Parameter(description = "指标类型") @RequestParam(required = false) String metricType,
            @Parameter(description = "开始时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @Parameter(description = "结束时间") @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        log.info("查询聚合指标, agentId: {}, metricType: {}", agentId, metricType);
        return ApiResponse.success(agentMetricService.getAggregatedMetrics(agentId, metricType, startTime, endTime));
    }

    @GetMapping("/{agentId}/summary")
    @PreAuthorize("hasAuthority('agent:metric:query')")
    @Operation(summary = "查询指标摘要", description = "获取最近7天的Agent性能摘要")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<Map<String, Object>> getMetricSummary(
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Parameter(description = "统计天数") @RequestParam(defaultValue = "7") int days) {
        log.info("查询指标摘要, agentId: {}, days: {}", agentId, days);
        
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days);
        
        return ApiResponse.success(agentMetricService.getAggregatedMetrics(agentId, null, startTime, endTime));
    }

    @GetMapping("/{agentId}/trend")
    @PreAuthorize("hasAuthority('agent:metric:query')")
    @Operation(summary = "查询趋势分析", description = "获取Agent性能趋势数据")
    @ApiResponses({
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "查询成功"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "401", description = "未授权"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "无权限"),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "404", description = "Agent不存在")
    })
    public ApiResponse<List<AgentMetric>> getMetricTrend(
            @Parameter(description = "Agent ID") @PathVariable String agentId,
            @Parameter(description = "天数") @RequestParam(defaultValue = "30") int days) {
        log.info("查询趋势分析, agentId: {}, days: {}", agentId, days);
        
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days);
        
        return ApiResponse.success(agentMetricService.getMetrics(agentId, startTime, endTime));
    }
}

